package chapter_24.udp.upload;

import java.io.*;
import java.net.*;

/**
 * Created by Administrator
 * Created time 2018/8/10 13:32.
 * 案例:文件上传工具(客户端)
 */
public class UploadClient {

    public static void main(String[] args) {

        // 运行前先删除文件
        File file = new File("./src/chapter_24/udp/upload/server.png");
        file.delete();

        System.out.println("客户端程序运行...");

        try (// 创建  对象,由系统分配可以使用的端口
             DatagramSocket datagramSocket = new DatagramSocket();
             // 由文件输出流创建缓冲输出流
             FileInputStream inputStream = new FileInputStream("./src/chapter_24/udp/upload/client.png");
             // 由文件输入流创建缓冲输入流
             BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        ) {
            // 创建远程主机和IP地址对象
            InetAddress address = InetAddress.getByName("localhost");

            // 缓冲区
            byte[] bytes = new byte[1024];
            // 首次从 Socket 读取数据
            int len = bufferedInputStream.read(bytes);

            while (len != -1) {
                // 创建数据报包对象
                DatagramPacket datagramPacket = new DatagramPacket(bytes, len, address, 6666);
                // 发送数据报包
                datagramSocket.send(datagramPacket);
                // 再次从文件流中读取数据
                len = bufferedInputStream.read(bytes);
            }

            // 创建数据报包对象
            DatagramPacket datagramPacket = new DatagramPacket("bye".getBytes(), 3, address, 6666);
            // 发送结束标识
            datagramSocket.send(datagramPacket);
            System.out.println("上传文件完成!");

        } catch (UnknownHostException e) {
            System.out.println("UnknownHostException");
        } catch (SocketException e) {
            System.out.println("SocketException");
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到!");
        } catch (IOException e) {
            System.out.println("IOException");
        }

    }

}
